package core;

import mobile.Mobile;
// import item.Item;

// import core.Core;

//import java.util.Arrays;



public class Combat 
{
	// private static Core cCore ; // Get base functions, like dice

	private Mobile[] cPlayerParty = new Mobile[6];	
	private Mobile cPlayerPet;

	public Combat()
	{
		// initialize cPlayerParty
		for (int i=0; i<cPlayerParty.length; i++)
			cPlayerParty[i]=null;
		cPlayerPet=null;
	}


	// Adds a player to the party, 
	// Returns 0 on success or returns 1 if we fail
	public int addPlayer(Mobile player)
	{
		int i;
		for (i=0; i<cPlayerParty.length; i++)
		{
			if ( cPlayerParty[i]==null)
			{
				cPlayerParty[i]=player;
				break;
			}
		}
		if (i <= cPlayerParty.length )
			return 0;
		else
			return 1;


	}

	public int removePlayer(int player)
	{
		Mobile remPlayer=cPlayerParty[player];	
		cPlayerParty[player]=null;
		renumberParty();
		return remPlayer.saveMe();

	}

	private void renumberParty()
	{
		Mobile[] tmpArray = new Mobile[cPlayerParty.length];
		for (int i=0; i<cPlayerParty.length;i++)
		{
			tmpArray[i]=null;
		}	
		for (int i=0; i<cPlayerParty.length;i++)
		{
			if ( cPlayerParty[i] != null )
			{
				// Loop through tmpArray and find the
				//  first free spot
				for (int j=0;j<tmpArray.length;j++)
				{
					if (tmpArray[j] == null)
					{
						tmpArray[j]=cPlayerParty[i];
						break;
					}
				}
			}
		}
		System.arraycopy(tmpArray, 0, cPlayerParty, 0, cPlayerParty.length);
	}


	public void printParty()
	{
		// TODO: type DEAD if the player has 0 hp.
		if (cPlayerPet != null)
			System.out.printf("S %10s %2s %4d %4d\n",
					cPlayerPet.getName(),
					cPlayerPet.getAc(),
					cPlayerPet.getHp(),
					cPlayerPet.getHpMax());
		
		for (int i=0; i<cPlayerParty.length;i++)
		{
			if ( cPlayerParty[i] != null )
			{
				System.out.printf("%1d %10s %2s %4d %4d\n",i,
						cPlayerParty[i].getName() ,
						cPlayerParty[i].getAc() ,
						cPlayerParty[i].getHp()  ,
						cPlayerParty[i].getHpMax()); 
			}
		}

	}
	
	public int movePlayer( int from, int to)
	{
		if (cPlayerParty[from] == null || cPlayerParty[to] == null)
			return 1;
		Mobile tmpPlayer = cPlayerParty[from];
		cPlayerParty[from]=cPlayerParty[to];
		cPlayerParty[to]=tmpPlayer;
		return 0;
	}
	
	// Returns 1 on hit, 0 on miss
	public int tryHit(Mobile attacker, Mobile defender)
	{
		// TODO: Real combat..
		int defenderAc= defender.getAc();
		int attackerAttackBonus = attacker.getAttackBonus();
		int dice=Core.dice(20,1);
		if (dice==20)
			return 1; // Automatic hit
		if (dice==1)
			return 0; //  Automatic miss
		if (  ( dice + attackerAttackBonus)  >= defenderAc ) 
			return 1;
		return 0;
		
	}
}




